package controller

import (
	"fmt"
	"math/rand"
	"service/components"
	"service/modules"
	"service/utils"
	"strconv"
	"strings"
	"time"

	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
)

// RegisterController 注册控制器
func RegisterController(ctx *gin.Context) {
	user := ctx.MustGet("user").(*modules.Users)
	err := modules.CreateUserService(user)
	if err != nil {
		utils.HandleFailResponse(ctx, "创建用户失败,请联系管理员~", nil)
		return
	}
	utils.HandleSuccessResponse(ctx, "帐号注册成功~", nil)
}

// LoginController 登录控制器
func LoginController(ctx *gin.Context) {
	user := ctx.MustGet("user").(*modules.Users)
	token, err := utils.GenerateToken(user)
	if err != nil {
		utils.HandleFailResponse(ctx, "系统生成Token失败~", nil)
		return
	}
	ip := ctx.ClientIP()
	ips := strings.Split(user.LoginIp, ",")
	if len(ips) >= 2 {
		user.LoginIp = strings.Join([]string{ips[1], ip}, ",")
	} else {
		user.LoginIp = ip
	}
	//if !user.IsLogin {
	//	user.IsLogin = true
	//} else {
	//	utils.HandleFailResponse(ctx, "账号已登录！", nil)
	//	return
	//}
	// SocketNotice
	components.DB.Model(modules.Users{}).
		Where("id = ?", user.Id).
		Updates(map[string]interface{}{
			"is_login":     user.IsLogin,
			"login_ip":     user.LoginIp,
			"edit_account": false,
		})
	utils.HandleSuccessResponse(ctx, "登录成功~", gin.H{
		"id":         user.Id,
		"token":      token,
		"department": user.Department,
	})

}

// GetAllUserController 获取所有用户的数据
func GetAllUserController(ctx *gin.Context) {
	users, count := modules.FindAllUserService()
	utils.HandleSuccessResponse(ctx, "查询完成", gin.H{
		"users":  users,
		"length": count,
	})
}

// UpdatedUserInfoController 更新用户数据
func UpdatedUserInfoController(ctx *gin.Context) {
	userBind := modules.Users{}
	err := ctx.ShouldBind(&userBind)
	if err != nil {
		utils.HandleFailResponse(ctx, "数据错误!", err.Error())
		return
	}
	_, err = govalidator.ValidateStruct(userBind)
	if err != nil {
		utils.HandleFailResponse(ctx, "数据类型不正确 不会处理的请联系管理员处理~", err.Error())
		return
	}
	fmt.Println("=> user ", userBind.ReadAccount, userBind.EditAccount)
	err = modules.UpdatedUserInfoService(userBind)
	if err != nil {
		utils.HandleFailResponse(ctx, "用户更新失败~", err.Error())
		return
	}
	utils.HandleSuccessResponse(ctx, "用户更新成功~", userBind)
}

// GetUserInfoController 获取返回给用户的数据
func GetUserInfoController(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 10)
	if err != nil {
		utils.HandleFailResponse(ctx, "id 数据 错误", nil)
		return
	}
	user, err := modules.FindUserByIdOmitPadService(id)
	if err != nil {
		utils.HandleFailResponse(ctx, err.Error(), nil)
		return
	}
	utils.HandleSuccessResponse(ctx, "获取用户信息", user)
}

func DeleteUserByIdController(ctx *gin.Context) {
	id := ctx.Param("id")
	err := modules.DeleteUserService(id)
	if err != nil {
		utils.HandleFailResponse(ctx, "用户删除失败~", nil)
		return
	}
	utils.HandleSuccessResponse(ctx, "删除成功~", id)
}

func GetUserInfoDetailController(ctx *gin.Context) {
	username := ctx.Query("username")
	phone := ctx.Query("phone")
	email := ctx.Query("email")
	sex := ctx.Query("sex")
	createdAt := ctx.Query("created_at")
	times := strings.Split(createdAt, ",")
	db := components.DB.Model(modules.Users{})
	if username != "" {
		db = components.DB.Where("user_name LIKE ?", "%"+username+"%")
	}
	if phone != "" {
		db = db.Where("phone LIKE ?", "%"+phone+"%")
	}
	if email != "" {
		db = db.Where("email LIKE ?", "%"+email+"%")
	}

	if sex != "" {
		db = db.Where("sex = ?", sex)
	}
	if createdAt != "" {
		db = db.Where("created_at > ? && created_at < ?", times[0], times[1])
	}

	// 执行查询
	var results []modules.Users
	err := db.Find(&results).Error
	if err != nil {
		results = []modules.Users{}
	}
	fmt.Println("找到了： ", results)
	utils.HandleSuccessResponse(ctx, "用户查询成功~", gin.H{
		"count": len(results),
		"users": results,
	})
}

func ResetPasswordController(ctx *gin.Context) {
	// 数据
	data := struct {
		Email      string `json:"email" form:"email"`
		VerifyCode string `json:"verify_code" form:"verify_code"`
		Password   string `json:"password" form:"password"`
	}{}
	err := ctx.ShouldBind(&data)
	if err != nil {
		utils.HandleFailResponse(ctx, "数据错误", nil)
		return
	}
	// 查找用户
	user, err := modules.FindUserByEmailService(data.Email)
	fmt.Println("FindUserByEmailService err: ", err)
	if err != nil {
		utils.HandleFailResponse(ctx, "没有该用户", nil)
		return
	}
	// 获取验证码
	verifyCode, err := components.RedisDB.Get(data.Email).Result()
	if err != nil {
		utils.HandleFailResponse(ctx, "该邮箱没有发送验证码！！！", nil)
		return
	}

	if verifyCode != data.VerifyCode {
		utils.HandleFailResponse(ctx, "验证码不对！！！ 请查看邮箱", nil)
		return
	}

	pass, _ := utils.HandlePwdEncryptionMd5(data.Password)
	u := modules.Users{}
	err = components.DB.Model(modules.Users{}).
		Where("id = ?", user.Id).
		Take(&u).
		Update("password", pass).Error
	if err != nil {
		utils.HandleFailResponse(ctx, "更新密码失败！ 请联系管理员", nil)
	}
	components.RedisDB.Del(data.Email)
	utils.HandleSuccessResponse(ctx, "密码重置成功， 返回登录 ", nil)

}

func SendCodeService(ctx *gin.Context) {
	data := struct {
		Email string `json:"email" form:"email"`
	}{}
	ctx.ShouldBind(&data)
	fmt.Println("-> ", data)
	rand.Seed(time.Now().UnixNano())
	res := ""
	for i := 0; i < 6; i++ {
		res += strconv.Itoa(rand.Intn(10))
	}
	err := components.RedisDB.Set(data.Email, res, time.Second*60*5).Err()
	if err != nil {
		utils.HandleFailResponse(ctx, "redis Error", nil)
		return
	}
	utils.SendSetPadEmail(data.Email, res)
	utils.HandleSuccessResponse(ctx, "验证码发送成功！ 请检查"+data.Email+"邮箱", nil)
}
